package android.twitter.clientroid;

import java.io.InputStream;
import java.net.URL;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class TwitterListAdapter extends ArrayAdapter<JSONObject>
{

	public TwitterListAdapter(Activity activity, List<JSONObject> imageAndTexts)
	{
		super(activity, 0, imageAndTexts);
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent)
	{

		Activity activity = (Activity) getContext();
		LayoutInflater inflater = activity.getLayoutInflater();

		// Inflate the views from XML
		View rowView = inflater.inflate(R.layout.feed, null);
		JSONObject jsonImageText = getItem(position);

		//////////////////////////////////////////////////////////////////////////////////////////////////////
		//The next section we update at runtime the text - as provided by the JSON from our REST call
		////////////////////////////////////////////////////////////////////////////////////////////////////
		
		// Set the text on the TextView and image on the ImageView
		ImageView imageAuthor = (ImageView) rowView.findViewById(R.id.image_author);
		TextView labelAuthor = (TextView) rowView.findViewById(R.id.label_author);
		TextView labelTime = (TextView) rowView.findViewById(R.id.label_time);
		TextView labelTweet = (TextView) rowView.findViewById(R.id.label_tweet);
		//textView.setBackgroundResource(R.drawable.speech_bubble_right);
		
		try
		{
			String avatar = (String)jsonImageText.get("avatar");
			String tweet = (String)jsonImageText.get("tweet");
			String auth = (String)jsonImageText.get("author");
			String date = (String)jsonImageText.get("tweetDate");
			if (date.length()>0)
			{
				imageAuthor.setImageDrawable(loadImageFromURL(avatar));
				labelAuthor.setText(Html.fromHtml(auth));
				labelTime.setText(Html.fromHtml(date));
				labelTweet.setText(Html.fromHtml(tweet));
			} else {
				labelAuthor.setText(Html.fromHtml(tweet) + "\n" + Html.fromHtml(auth));
			}
		}
		catch (JSONException e)
		{
			labelAuthor.setText("JSON Exception");
		}

		return rowView;

	}
	
	private Drawable loadImageFromURL(String url)
    {
	    try
	    {
		    InputStream is = (InputStream) new URL(url).getContent();
		    Drawable d = Drawable.createFromStream(is, "src");
		    return d;
	    }
	    catch (Exception e)
	    {
	    	System.out.println(e);
	    	return null;
	    }
    }

}